﻿using System;
using System.Web.UI;
using StructureMap;
using Tarantino.Core.Commons.Services.Repositories;
using Tarantino.Core.Commons.Services.Security;
using Tarantino.Samples.Core.Services.Repositories;
using Tarantino.Samples.Core.Services.Security;

namespace Tarantino.Samples.UI.SecureSite
{
	public partial class Login : Page
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			btnForgotPassword.Click += btnForgotPassword_OnClick;
			btnLogin.Click += btnLogin_OnClick;
			btnAddUser.Click += btnAddUser_OnClick;
		}

		private void btnAddUser_OnClick(object sender, EventArgs e)
		{
			string email = txtNewUserEmailAddress.Text;
			string password = txtNewUserPassword.Text;
			string firstName = txtFirstName.Text;
			string lastName = txtLastName.Text;
			bool rememberMe = chkNewUserRememberMe.Checked;

			INewUserService newUserService = ObjectFactory.GetInstance<INewUserService>();
			string userFeedback = newUserService.AddNewUser(email, password, firstName, lastName, rememberMe, getRepository());

			lblResults.Text = userFeedback;
		}

		private void btnForgotPassword_OnClick(object sender, EventArgs e)
		{
			IForgottenPasswordService passwordService = ObjectFactory.GetInstance<IForgottenPasswordService>();
			string userFeedback = passwordService.SendEmailTo(txtEmailAddress.Text, getRepository());
			lblResults.Text = userFeedback;
		}

		private void btnLogin_OnClick(object sender, EventArgs e)
		{
			performLogin(txtEmailAddress.Text, txtPassword.Text, chkRememberMe.Checked, lblResults);
		}

		private void performLogin(string emailAddress, string password, bool rememberMe, ITextControl resultsLabel)
		{
			ILoginService loginService = ObjectFactory.GetInstance<ILoginService>();

			string userFeedback = loginService.Login(emailAddress, password, rememberMe, getRepository());
			resultsLabel.Text = userFeedback;
		}

		private ISystemUserRepository getRepository()
		{
			IPersistentObjectRepository objectRepository = ObjectFactory.GetInstance<IPersistentObjectRepository>();
			return new SystemUserRepository(objectRepository);
		}
	}
}